#!/bin/bash
displayUsage () {
    echo "Purpose:  Detect letterbox borders on a video file for use by the ffmpeg crop option." >&2
    echo "Usage:    $NAME [-options] videofile" >&2
    echo "Options:  -d sec : Run for this duration of seconds during detection (default=30)" >&2
    echo "          -i     : Run interactive.  Show crop parameters repeatedly as the video plays." >&2
    echo "Example:  $NAME videos/example/movie1.vob" >&2
    echo "          Would output the crop parameters such as '720:480:0:0'" >&2
}

NO_ARGS=1
E_OPTERROR=65
E_EXECUTION_ERROR=1
NAME=${0##*/}
DURATION='30'
INTERACTIVE='False'

# Test that required commands are in the path
for CMD in ffmpeg sed; do
   type $CMD &> /dev/null
   if [ $? != "0" ]; then
      echo "The command '$CMD' is required and is not in your path" >&2
      exit $E_EXECUTION_ERROR 
   fi
done

while getopts ":d:i" Option
do
    case $Option in
	d) DURATION=$OPTARG;;
	i) INTERACTIVE='True';;
	*) echo "Error: unknown option -$OPTARG" >&2
	   displayUsage
	   exit $E_OPTERROR;;
    esac
done

shift $(($OPTIND - 1))

if [ $# -lt "$NO_ARGS" ]
then
    displayUsage
    exit $E_OPTERROR
fi

INPUTFILE="$1"

if [[ ! -e "$INPUTFILE" ]]
then
    echo "Error: Video file \"$INPUTFILE\" does not exist" >&2
    exit $E_OPTERROR
fi

if [[ "$INTERACTIVE" == 'True' ]]
then
        ffmpeg -t $DURATION -i "${INPUTFILE}" -vf cropdetect -f rawvideo -an -y /dev/null 2>&1 |\
	sed -n 's/crop=/&/p'
else
        ffmpeg -t $DURATION -i "${INPUTFILE}" -vf cropdetect -f rawvideo -an -y /dev/null 2>&1 |\
	sed -n 's/crop=/&/p' |\
	sed '$!d' |\
	sed -e 's/.*crop=//;s/).*$//'
fi
